package dk.kapetanovic.jaft.action;


import java.io.File;
import java.io.IOException;

import dk.kapetanovic.jaft.action.io.FileHandler;
import dk.kapetanovic.jaft.transaction.Transaction;

public class RenameAction implements Action {

	private File source;
	private File dest;
	private transient Transaction transaction;
	private FileHandler handler;
	
	public RenameAction(File source, File dest, Transaction transaction) {
		this.dest = dest;
		this.source = source;
		handler = new FileHandler();
		setTransaction(transaction);
	}

	@Override
	public Object execute() throws IOException {
		handler.rename(source, dest);
		return null;
	}

	@Override
	public Transaction getTransaction() {
		return transaction;
	}

	@Override
	public void setTransaction(Transaction transaction) {
		this.transaction = transaction;
		handler.setBackupDir(transaction.
			getTransactionManager().getBackupDir());
	}

	@Override
	public void undo() throws IOException {
		if(dest.exists())
			handler.rename(dest, source);
	}
	
	@Override
	public String toString() {
		return "RenameAction [source=" + source + ", dest=" + dest + "]";
	}

	@Override
	public void cleanup() {}

	@Override
	public void close() {}

	@Override
	public void prepare() throws IOException {
		if(dest.exists())
			throw new IOException("Destination file already exists: " + 
				dest.getAbsolutePath());
	}
}
